package com.longtop.sp.mapdao.dialect.oracle;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.longtop.sp.mapdao.Delete;
import com.longtop.sp.mapdao.dialect.ConfigProperties;
import com.longtop.sp.mapdao.impl.AbstractOperate;
import com.longtop.sp.mapdao.meta.IPrimaryKey;
import com.longtop.sp.mapdao.meta.TableMetaData;
import com.longtop.sp.mapdao.meta.TableMetaDataPool;

public class OracleDelete extends AbstractOperate implements Delete {
	private static Log log = LogFactory.getLog(OracleDelete.class);
	private String sql;

	@Override
	public int executeImpl() throws Exception {
		IPrimaryKey pk = this.pkFactory.createPrimarykey(jdbcTemplate,
				tableName,ConfigProperties.getValue());
		TableMetaData rsmt = TableMetaDataPool.getMetaData(jdbcTemplate,
				tableName);
		FieldEntryList fields = new FieldEntryList(rsmt, tmData);
		String pkAndValue = pk.getPrimaryKeyAndValue(tmData, rsmt);
		sql = buildSql(fields, pkAndValue);
		return internalExecute();
	}

	private int internalExecute() throws Exception {
		return this.jdbcTemplate.update(sql);
	}

	private String buildSql(FieldEntryList fields, String pkAndValue)
			throws Exception {
		// 没有发现可以插入的字段，不需要执行，抛出异常
		if (fields.getColumnCount() == 0) {
			throw new Exception("Map中的数据与数据库表的字段名均不相同，没有发现可以插入的字段。");
		}

		// 构造一个insert into tableName(field1,...) values(... ...)语句
		StringBuffer sqlBuffer = new StringBuffer();
		sqlBuffer.append("DELETE FROM " + tableName + " WHERE " + pkAndValue);

		String sql = new String(sqlBuffer);
		if (log.isDebugEnabled()) {
			log.debug("插入的sql语句=" + sql);
		}
		return sql;
	}

}
